import logging
import os
import sys
import win32api
import win32con
from logging import handlers
from win32com import client as winclient
from imessagefilter import CMessageFilter

# 关闭标签服务
os.system('taskkill /F /T /IM DecSvr.exe')
os.system('taskkill /F /T /IM Decseclt.exe')
os.system('taskkill /F /T /IM DecsecltStub64.exe')

# 关闭office进程
os.system('taskkill /F /IM Word.exe')
os.system('taskkill /F /IM winword.exe')
os.system('taskkill /F /IM PowerPoint.exe')
os.system('taskkill /F /IM powerpnt.exe')
os.system('taskkill /F /IM Excel.exe')
os.system('taskkill /F /IM wps.exe')
paths = ['C:\\', 'D:\\', 'E:\\', 'F:\\', 'G:\\', 'H:\\']
# 测试路径
# paths = ['D:\\doctest']
# 需要删除的文件路径
delpath = []
# 需要删除的文件名
delfiles = []
# 注册表注册
CMessageFilter.register()
# office进程创建
word = winclient.DispatchEx("Word.Application")
word.Visible = False
word.DisplayAlerts = False
powerpoint = winclient.DispatchEx("PowerPoint.Application")
powerpoint.Visible = True
powerpoint.DisplayAlerts = False
excel = winclient.DispatchEx("Excel.Application")
excel.Visible = False
excel.DisplayAlerts = False

# 日志级别关系映射
level_relations = {
    'debug': logging.DEBUG,
    'info': logging.INFO,
    'warning': logging.WARNING,
    'error': logging.ERROR,
    'crit': logging.CRITICAL
}


def isdocuments(filename):
    return filename.upper().endswith('.DOC') or filename.upper().endswith('.PPT') or filename.upper().endswith(
        '.XLS')


def _get_logger(filename, level='info'):
    # 创建日志对象
    log = logging.getLogger(filename)
    # 设置日志级别
    log.setLevel(level_relations.get(level))
    # 日志输出格式
    fmt = logging.Formatter('%(asctime)s %(thread)d %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
    # 输出到控制台
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setFormatter(fmt)
    # 输出到文件
    # 日志文件按天进行保存，每天一个日志文件
    # file_handler = handlers.TimedRotatingFileHandler(filename=filename, when='D', backupCount=1, encoding='utf-8')
    # 按照大小自动分割日志文件，一旦达到指定的大小重新生成文件
    file_handler = handlers.RotatingFileHandler(filename=filename, maxBytes=1 * 1024 * 1024 * 1024, backupCount=1,
                                                encoding='utf-8')
    file_handler.setFormatter(fmt)

    log.addHandler(console_handler)
    log.addHandler(file_handler)
    return log


def find_file():
    global zipf
    zlog = _get_logger('./文件转换日志.txt', 'info')
    i = 0
    for path in paths:
        for root, lists, files in os.walk(path):
            for file in files:
                nfile = file
                if ('[' in file or ']' in file) and isdocuments(nfile):
                    nfile = file.replace('[', '_').replace(']', '_')
                    os.rename(os.path.join(root, file), os.path.join(root, nfile))
                originalpath = os.path.join(root, nfile)
                if '$' not in nfile:
                    try:
                        if nfile.upper().endswith('.DOC'):
                            i += 1
                            zlog.info('[第%d个文件]-----文件路径：[%s]' % (i, originalpath))
                            wordrewrite(originalpath)
                            os.system(f'del "{originalpath}" /F')
                        if nfile.upper().endswith('.PPT'):
                            i += 1
                            zlog.info('[第%d个文件]-----文件路径：[%s]' % (i, originalpath))
                            powerrewrite(originalpath)
                            os.system(f'del "{originalpath}" /F')
                        if nfile.upper().endswith('.XLS'):
                            i += 1
                            zlog.info('[第%d个文件]-----文件路径：[%s]' % (i, originalpath))
                            excelrewrite(originalpath)
                            os.system(f'del "{originalpath}" /F')
                    except BaseException as e:
                        delpath.append(originalpath)
                        delfiles.append(nfile)
                        zlog.error(e)
                else:
                    if isdocuments(nfile):
                        delpath.append(originalpath)
                        delfiles.append(nfile)
    elog = _get_logger('./失败文件日志.txt', 'info')
    for filepath in delpath:
        elog.info(f'需要手动删除文件地址：{filepath}')
    clearoffice()
    win32api.MessageBox(0, '转换完毕，请在软件根目录下查看失败文件日志，手动删除！\n点击确定按钮关闭程序', '运行提示',
                        win32con.MB_OK)


def wordrewrite(filename):
    out_name = filename.lower().replace(".doc", '.docx')
    if os.path.exists(out_name):
        out_name = filename.replace('.doc', '_re.docx')
    doc = word.Documents.Open(filename)
    doc.SaveAs(out_name, 12)
    doc.Close()


def powerrewrite(filename):
    out_name = filename.lower().replace(".ppt", '.pptx')
    if os.path.exists(out_name):
        out_name = filename.replace('.ppt', '_re.pptx')
    ppt = powerpoint.Presentations.Open(filename)
    ppt.SaveAs(out_name, 11)
    ppt.Close()


def excelrewrite(filename):
    out_name = filename.lower().replace(".xls", '.xlsx')
    if os.path.exists(out_name):
        out_name = filename.replace('.xls', '_re.xlsx')
    xls = excel.Workbooks.Open(filename)
    xls.SaveAs(out_name, 51)
    xls.Close()


def clearoffice():
    global word, powerpoint, excel
    word.Quit()
    del word
    powerpoint.Quit()
    del powerpoint
    excel.Quit()
    del excel
    os.system('taskkill /F /IM Word.exe')
    os.system('taskkill /F /IM winword.exe')
    os.system('taskkill /F /IM PowerPoint.exe')
    os.system('taskkill /F /IM powerpnt.exe')
    os.system('taskkill /F /IM Excel.exe')
    os.system('taskkill /F /IM wps.exe')
    try:
        os.startfile('C:\\Program Files\\TagShield\\DecSvr.exe')
        os.startfile('C:\\Program Files\\TagShield\\Decseclt.exe')
    except BaseException:
        pass
    CMessageFilter.revoke()


if __name__ == '__main__':
    find_file()
